package cn.ac.cintcm.prespring.cluster.name;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.solr.core.Config;

public class FjName2Word {
	private static String fjUrl = Config.getInstanceDir()+ "data/originalData/PRES_FJ_Name.txt";
	
	private static String outputText = Config.getInstanceDir()+ "data/tempFiles/PRES_FJ_Name_Word.txt";
	
	public static void main(String[] args) throws Exception{
		generateWordText(readFromText());
	}
	
	public static final char[] stopWords(){
		char[] stopwords=new char[30];
		return stopwords;
	}
	
	public boolean isStopWord(char ch){
		
		return false;
	}
	
	/**
	 * @return map(FjName,fangjiIds)
	 */
	public static Map<String, String> readFromText() throws Exception {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(fjUrl), "UTF8"));
		String line = "";
		Map<String, String> map = new HashMap<String, String>();
		while ((line = reader.readLine()) != null) {
			String[] s = line.split(":");
			if (s.length == 2) {
				String fjName= s[0];
				String fjIds = s[1];
				map.put(fjName,fjIds);
				//System.out.println(fjName+" ----- "+fjIds);
			}
		}	
		reader.close();
		return map;
	}
	
	public static void generateWordText(Map<String,String> map) throws Exception{
		if(map==null ||map.size()==0){
			return;
		}
		System.err.println("generate word:");
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(outputText, false), "UTF8"));
		StringBuilder sb = new StringBuilder();
		
		Set<String> names=map.keySet();		
		Iterator<String> iter=names.iterator();		
		while(iter.hasNext()){
			String name=iter.next();
			if(name.length()==2){
				sb.append(name + ":"+map.get(name));				
				writer.append(sb.toString());
				writer.write("\r\n");
				sb.setLength(0);
			}else if(name.length()==3){
				sb.append(name.substring(0,name.length()-1)+":"+map.get(name));					
				writer.append(sb.toString());
				writer.write("\r\n");
				sb.setLength(0);
			}else if(name.length()>3){
				int beginIndex=0;
				int endIndex=beginIndex+2;
				while(beginIndex!=(name.length()-2)){
					while(endIndex!=name.length()){
						String word=name.substring(beginIndex,endIndex);
						endIndex++;
						sb.append(word+":"+map.get(name));
						writer.append(sb.toString());
						sb.setLength(0);
						writer.write("\r\n");
						//System.out.println(word);
					}
					beginIndex++;
					endIndex=beginIndex+2;
				}
			}
		}
		writer.close();
		map.clear();
		map = null;
	}
}
